package com.netty.esc.service.http.impl;

import com.netty.esc.Interceptor.annotation.FuckAll;
import com.netty.esc.common.enums.SMSEnum;
import com.netty.esc.service.http.SendSMS;
import com.netty.esc.utils.MessageUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

/**
 * @author: ext.zhaoyang17
 * @date: 2022.11.09
 */
@Service
@FuckAll
public class SendSMSImpl implements SendSMS {

    @Resource
    RedisTemplate<String,Object> redisTemplate;

    @Override
    public String sendSMSToRedis(String telephone, SMSEnum smsEnum) {
        //先看看缓存中是否短信验证码还未失效，如果还有效则不发送短信
        String code = (String)redisTemplate.opsForValue().get(smsEnum.getValue() + telephone);
        if (StringUtils.isNotEmpty(code)){
            return null;
        }
        //调用短信服务
        code = MessageUtil.sendMessage(telephone);
        //放入redis中，失效时间为5分钟
        redisTemplate.opsForValue().set(smsEnum.getValue() + telephone,code,500, TimeUnit.MINUTES);
        return code;
    }

    @Override
    public boolean verificationSMS(String telephone, String code, SMSEnum smsEnum) {
        String codeDb = (String)redisTemplate.opsForValue().get(smsEnum.getValue() + telephone);
        return !StringUtils.isEmpty(codeDb) && code.equals(codeDb);
    }
}
